<?php
if(!defined('BASEPATH'))
		exit('No direct script access allowed');
		
class Authentication {
	var $_id_user = 0;
	var $_login = "";
	var $_password = "";
	var $_role = "";
	var $_auth = FALSE;
	function Authentication($auto = TRUE)
	{
		if($auto)
		{
			$CI =& get_instance();
			$CI->load->library('session');
			if($this->login($CI->session->userdata('username'), $CI->session->userdata('password')))
			{
				$this->_id_user = $CI->session->userdata('id_user');
				$this->_login = $CI->session->userdata('username');
				$this->_password = $CI->session->userdata('password');
				$this->_role = $CI->session->userdata('role');
			}
		}
	}
	function getId(){return $this->_id_user;}
	function getLogin(){return $this->_login;}
	function getPassword(){return $this->_password;}
	function getRol(){return $this->_role;}
	
	function login($username= "", $password = "")
	{
		if(empty($username)||empty($password))
			return FALSE;

		$CI =& get_instance();		

		$sql = "SELECT * FROM `usuario` WHERE `login_usu`=? AND `pass_usu`=?";
		$query = $CI->db->query($sql, array($username, $password));

		//login ok
		if($query->num_rows()==1)
		{
			$row = $query->row();

			$CI->session->set_userdata('id_user', $row->id_user);//id_user//userid
			$this->_id_user = $row->userid;
			$CI->session->set_userdata('name', $row->nombre_usu.' '.$row->apellido_usu);//name//username
			$this->_login = $username;
			$CI->session->set_userdata('password', $password);
			$this->_password = $row->password;
			$CI->session->set_userdata('role', $row->tipo_usu);
			$this->_role= $row->role;
			
			$id_user = $this->_id_user = $row->id_user;
			$roles = $this->_role = $row->tipo_usu;
			
			$ip = $_SERVER['REMOTE_ADDR']; 
			$dat=date("Y-m-d G:i:s");

			$this->_auth = TRUE;

			return TRUE;
		}
		else
		{
			$this->_auth = FALSE;
			$this->logout();

			return FALSE;
		}
	}
	function logout()
	{
		$CI =& get_instance();
		$CI->session->sess_destroy();        
		  
	}
    function isLogin(){
		$CI =& get_instance();
		$usuario_login = $CI->session->userdata('name');
		$usuario_password = $CI->session->userdata('password');
		if (empty($usuario_login) && empty($usuario_password)) {
		   return FALSE;
		}else return TRUE;
	}
    
	function check($level = 0, $strict = TRUE)
	{
		if(!$this->_auth)
			return FALSE;

		if($strict)
		{
			if($level == $this->_level)
				return TRUE;
			else
				return FALSE;
		}
		else
		{
			if($level <= $this->_level)
				return TRUE;
			else
				return FALSE;
		}
	}
}
?>